package com.peanut.baby.repository;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.peanut.baby.AppConfig;
import com.peanut.baby.model.PTag;
import com.peanut.baby.model.User;
import com.peanut.baby.repository.local.UserLocalRepository;
import com.peanut.baby.util.PrefUtil;
import com.peanut.devlibrary.util.StringUtil;
import com.tencent.mars.xlog.Log;

import java.util.List;

/**
 * Created by anonymouslystudio on 2017/7/10.
 */

public class UserRepository {
    private static final String TAG = UserRepository.class.getSimpleName();
    private static final class InstanceHolder{
        public static final UserRepository _instance = new UserRepository();
    }

    public static UserRepository getInstance(){
        return InstanceHolder._instance;
    }

    /**
     *
     * @return
     */
    public User getCurrentUser(){
        String savedUser = PrefUtil.getString(AppConfig.PrefConfig.PREF_CURRENT);
        if(StringUtil.isNullOrEmpty(savedUser)){
            return null;
        }
        Gson gson = new Gson();
        User user = gson.fromJson(savedUser,User.class);
        return user;
    }

    /**
     *
     * @return
     */
    public boolean updateCurrentUser(User user){
       if(user == null){
           PrefUtil.saveString(AppConfig.PrefConfig.PREF_CURRENT,"");
       }else{
           Gson gson = new Gson();
           String jsonString = gson.toJson(user);
           PrefUtil.saveString(AppConfig.PrefConfig.PREF_CURRENT,jsonString);
       }
       return true;
    }

    public User getUser(String userId){
        User user = UserLocalRepository.getInstance().getUser(userId);
        return user;
    }

    public boolean updateUser(User user){
        boolean flag = true;
        return flag;
    }


    /**
     *
     * @return
     */
    public List<PTag> getTags(){
        String savedTags = PrefUtil.getString(AppConfig.PrefConfig.PREF_TAGS);
        Log.d(TAG,"savedTags "+savedTags);
        if(StringUtil.isNullOrEmpty(savedTags)){
            return null;
        }
        Gson gson = new Gson();

        List<PTag> tags = gson.fromJson(savedTags, new TypeToken<List<PTag>>(){}.getType());
        return tags;
    }

    /**
     *
     * @return
     */
    public boolean updateTags(List<PTag> tags){
        if(tags == null){
            PrefUtil.saveString(AppConfig.PrefConfig.PREF_TAGS,"");
        }else{
            Gson gson = new Gson();
            String jsonString = gson.toJson(tags);
            PrefUtil.saveString(AppConfig.PrefConfig.PREF_TAGS,jsonString);
        }
        return true;
    }

}
